package servlet;

import bo.UserBO;
import java.io.IOException;
import java.io.PrintWriter;
import javabean.UserBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserBO userBO = new UserBO();
        try {
            UserBean user = userBO.isExist(username, password);
            HttpSession session = req.getSession();
            session.setAttribute("userbean", user); //dua ten username vao session
            if (user != null && user.getRole().equals("admin")) {
                resp.sendRedirect("jsp/Account/AdminFunctions.jsp");
            }
            else {
                if (user != null && user.getRole().equals("user")) {
                    resp.sendRedirect("./jsp/Account/UserFunctions.jsp");
                }
                else {
                    resp.sendRedirect("./jsp/Account/LoginFailed.jsp");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }
}
